<template>
	<Header title="认证"></Header>
	<view class="card-wrap">
		<view class="item">
			<ocr-navigator @onSuccess="success" certificateType="idCard" opposite="{{false}}">
				<view class="button-mask"></view>
				<image v-if="fields.card_front" :src="fields.card_front" mode="widthFix" />
				<view v-else class="card-default">身份证正面识别</view>
			</ocr-navigator>
		</view>
		<view class="item">
			<ocr-navigator @onSuccess="success" certificateType="idCard" opposite="{{true}}">
				<view class="button-mask"></view>
				<image v-if="fields.card_reverse" :src="fields.card_reverse" mode="widthFix" />
				<view v-else class="card-default">身份证反面识别</view>
			</ocr-navigator>
		</view>
	</view>
	
	<up-form ref="formRef" :model="fields" :rules="rules">
		<view class="label-layout">
			<view class="label-left">姓名</view>
			<view class="label-right">
				<up-form-item prop="user_name" borderBottom>
					<up-input v-model="fields.user_name" border="none"></up-input>
				</up-form-item>
			</view>
		</view>
		<view class="label-layout">
			<view class="label-left">身份证</view>
			<view class="label-right">
				<up-form-item prop="card_id" borderBottom>
					<up-input v-model="fields.card_id" border="none"></up-input>
				</up-form-item>
			</view>
		</view>
		
		<up-form-item label="性别" prop="gender" borderBottom>
			<up-radio-group v-model="fields.gender" placement="row">
				<up-radio label="男" name="男"></up-radio>
				<up-radio label="女" name="女"></up-radio>
			</up-radio-group>
		</up-form-item>
		<up-form-item label="手机号" prop="phone" borderBottom>
			<view class="get-phone-wrap">
				<up-input v-model="fields.phone" border="none" maxlength="11"></up-input>
				<button class="get-phone-button" open-type="getPhoneNumber" @getphonenumber="getphonenumber">授权获取手机号</button>
			</view>
		</up-form-item>
		<up-form-item label="邮箱" prop="email" borderBottom>
			<up-input v-model="fields.email" border="none"></up-input>
		</up-form-item>
		<up-form-item label="出生日期" prop="birth_date" borderBottom>
			<view style="position: relative;">
				<view @click="state.showDate = true" style="position: absolute; left: 0;top: 0;z-index: 10; width: 100%; height: 90rpx;"></view>
			</view>
			<up-datetime-picker ref="datetimePickerRef" format="YYYY-MM-DD" :formatter="formatter" hasInput :show="state.showDate" v-model="fields.birth_date" mode="date" @confirm="confirmDate"></up-datetime-picker>
		</up-form-item>
		<up-form-item label="省市区" prop="birth_date" borderBottom>
			<AreaComponent @confirm="areaConfirm" />
		</up-form-item>
		<up-form-item label="详细地址" prop="address" borderBottom>
			<up-textarea v-model="fields.address" placeholder="请输入内容" ></up-textarea>
		</up-form-item>
	</up-form>
	<view @click="submit">确认提交资料</view>
	<FooterButton :button="buttonList" />
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { area, getPhone, userauth } from "@/api/public.js"
import { useStore } from "vuex"
import { timestampToDate } from "@/utils/date"
import { onReady } from "@dcloudio/uni-app";
import AreaComponent from "@/components/area/index.vue"
import FooterButton from "@/components/footerButton/index.vue"
const store = useStore()

const state = reactive({
	showDate: false,
})
const formRef = ref(null)
const fields = reactive({
	card_front: "",
	card_reverse: "",
	user_name: "",
	card_id: "",
	gender: "男",
	phone: "",
	email: "",
	birth_date: "",
	province: "",
	city: "",
	area: "",
	address: ""
})

const buttonList = reactive([
	{ 
		label: "认证", 
		type: "success", 
		span: 6,
		callback: () => {
			
		},
		beforeChange: () => submit()
	},
	{ label: "缴费", type: "primary", span: 6 },
])

const rules = reactive({
	user_name: [
		{ type: 'string', required: true,  message: '请填写姓名', trigger: ['blur', 'change'] }
	],
	card_id: [
		{ type: 'string', required: true,  message: '请填写身份证', trigger: ['blur', 'change'] }
	],
	phone: [
		{ type: 'string', required: true,  message: '请填写手机号', trigger: ['blur', 'change'] }
	],
})

const areaConfirm = (ids) => {
	fields.province = ids[0]
	fields.city = ids[1]
	fields.area = ids[2]
}
const confirmDate = (val) => {
	fields.birth_date = timestampToDate(val.value)
	state.showDate = false
}

const datetimePickerRef = ref(null);

const formatter = (type, value) => {
  if (type === 'year') {
    return `${value}年`;
  }
  if (type === 'month') {
    return `${value}月`;
  }
  if (type === 'day') {
    return `${value}日`;
  }
  return value;
};
/**
 * 身份证识别成功
 */
const success = (data) => {
	const result = data.detail
	const image = result.image_path
	const type = result.type
	// 更新字段
	if(type === 0) {
		fields.user_name = result.name.text
		fields.card_id = result.id.text
		fields.gender = result.gender.text
	}
	
	uni.uploadFile({
		url: `http://book.web-jshtml.cn/view/upload`,
		filePath: data.detail.image_path,
		name: 'files',
		header: {
			'content-type': 'application/x-www-form-urlencoded',
		},
		success: (res) => {
			console.log('res', res)
			if(res.statusCode === 200) {
				const data = JSON.parse(res.data)
				if(type === 0) {
					fields.card_front = data.content.files_path
				}else{
					fields.card_reverse = data.content.files_path
				}
			}
		}
	});
}
/**
 * 获取手机号
 */
const getphonenumber = (e) => {
	console.log('e', e)
	const detail = e.detail
	if(detail.errMsg === 'getPhoneNumber:ok') {
		getPhone({ code: detail.code}).then(res => {
			fields.phone = res.content
		})
	}
}

const submit = () => {
	return new Promise((resolve, reject) => {
		if(!fields.card_front || !fields.card_reverse) {
			wx.showToast({
				title: "请上传身份证",
				icon: "none"
			})
			reject()
			return
		}
		formRef.value.validate().then(res => {
			if(res) {
				wx.showLoading({
				  title: '加载中',
				})
				userauth({
					...fields,
					gender: fields.gender === '男' ? 1 : 0
				}).then(() => {
					wx.showToast({
						title: "认证成功",
						icon: "none"
					})
					store.commit('app/SET_USER_STATUS', 2)
					// 返回上一个页面，但不会刷新页面
					uni.navigateBack({ delta:1 })
					resolve()
				})
			}
		})
	})
	
	// console.log(111, fields)
	// store.commit('app/SET_USER_STATUS', 2)
	// 返回上一个页面，但不会刷新页面
	// uni.navigateBack({ delta:1 })
}


onReady(() => {
  // 微信小程序需要用此写法
  datetimePickerRef.value.setFormatter(formatter);
});


</script>

<style lang="scss" scoped>
	.card-wrap {
		padding: 26rpx 28rpx;
		display: flex;
		align-items: center;
		column-gap: 28rpx;
		.item {
			position: relative;
			background: #FFFFFF;
			height: 190rpx;
			border-radius: 8rpx;
			border: 1px solid #DDDDDD;
			flex: 1;
			width: 0;
		}
		image {
			width: 100%;
		}
		.card-default {
			width: 100%;
			height: 190rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #999999;
			font-size: 20rpx;
		}
	}
	.button-mask {
		position: absolute;
		left: 0;
		top: 0;
		z-index: 10;
		width: 100%;
		height: 190rpx;
	}
	.get-phone-wrap {
		display: flex;
		align-items: center;
	}
	.get-phone-button {
		font-size: 20rpx;
		border: 1px solid #3c9cff;
		background-color: #3c9cff;
		color: #fff;
	}
	.label-layout {
		display: flex;
		align-items: center;
		position: relative;
		&::after {
			content: "";
			position: absolute;
			left: 0;
			right: 0;
			bottom: 0;
			border-bottom: 1px solid #E5E5E5;
			transform: scaleY(0.5);
		}
		.label-left {
			width: 150rpx;
			padding-right: 16rpx;
			text-align: right;
		}
		.label-right {
			flex: 1;
			width: 0;
		}
	}
</style>
